import json


from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger
from app.monitor_metrics.models.prom_alarm_group import PromAlarmGroup
from app.monitor_metrics.models.prom_alarm_set import PromAlarmSet
from app.monitor_metrics.handlers.prom_alarm_set_handler import PromAlarmSetHandler
from common.welab_k8s.k8s_pod import K8sPod
from common.welab_k8s.k8s_prometheus import K8sPrometheus


class PromAlarmGroupHandler():
    """  PromAlarmRuleGroup Handler
    """
    def __init__(self):
        self.k8s_prometheus = K8sPrometheus()
        self.prom_alarm_set_handler = PromAlarmSetHandler()



    def get_alarm_group_search(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段模糊匹配，获取告警规则组信息
        """
        try:
            field_info = {field: value}
            order_info = {"classes": "asc", "name": "asc"}
            result = PromAlarmGroup.filter_by_field_search(db, page, per_page, field_info, order_info)
            if not result:
                logger.warning(f"get alarm group search, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get alarm group search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result

    def get_alarm_group_match(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段完全匹配，获取告警规则组信息
        """
        try:
            result = PromAlarmGroup.filter_by_field_match(db, page, per_page, {field: value})
            if not result:
                logger.warning(f"get alarm group match, result is null => {field}:{value}")
                return False

        except Exception as e:
            message = f"get alarm group match by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result


    def get_alarm_group_rule(self, db: Session, uuid: int):
        """
        根据规则组的uuid, 获取规则组内的告警规则信息
        """
        try:
            if not PromAlarmGroup.get_object_by_uuid(db, uuid):
                logger.error(f"get alarm group rule, uuid:{uuid} not exist")
                return False, None
            alarm_group_info = PromAlarmGroup.get_object_info_by_uuid(db, uuid)
            alarm_rules = alarm_group_info["alarm_rules"]
            # 过滤内部标签
            for rule in alarm_rules:
                rule["labels"] = {
                    key: value
                    for key, value in rule["labels"].items()
                    if not key.startswith("i_")
                }
                rule["annotations"] = {
                    key: value
                    for key, value in rule["annotations"].items()
                    if key not in ["value", "message"]
                }
        except Exception as e:
            message = f"get alarm group match by uuid:{uuid} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, alarm_rules


    def add_alarm_group(self, db: Session, data: dict):
        """
        增加告警规则组，满足api调用时，实时更新到prometheus
        """
        try:
            # 添加到数据
            result = self.add_alarm_group_to_database(db, data)
            if not result:
                logger.error(f"add alarm group to database failed")
                return False

            # 更新到prometheus rule
            result = self.prom_alarm_set_handler.alarm_set_sync_prometheus_rule(db, data["alarm_set_uuid"])
            if not result:
                # 更新失败，清理数据
                alarm_group_info = PromAlarmGroup.get_object_info_by_name(db, data["name"])
                self.delete_alarm_group_to_database(db, alarm_group_info)

                logger.error(f"add_alarm_group: update prometheus rule failed")
                return False
        except Exception as e:
            message = f"add alarm group error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)
        return True




    def add_alarm_group_to_database(self, db: Session, data: dict):
        """
        创建告警规则组到数据库
        """
        try:
            alarm_group_object = PromAlarmGroup.get_object_by_name(db, data["name"])
            if alarm_group_object:
                # 如果存在， 则异常返回
                logger.error(f"add alarm group failed,{data['name']} was exist")
                return False

            alarm_set_object = PromAlarmSet.get_object_by_uuid(db, data["alarm_set_uuid"])
            if not alarm_set_object:
                # 如果存在， 则异常返回
                logger.error(f"add alarm group failed, alarm_set_uuid:{data['alarm_set_uuid']} not exist")
                return False

            # 增加到数据库
            data["classes"] = alarm_set_object.classes
            result = PromAlarmGroup.add(db, data)
            if not result:
                logger.error(f"add alarm group to database failed")
                return False
        except Exception as e:
            logger.exception(f"add alarm group error => {e}")
            return False

        return True


    def update_alarm_group(self, db: Session, data: dict):
        """
        更新告警规则组，满足api调用时，实时更新到prometheus
        """
        try:
            alarm_group_object = PromAlarmGroup.get_object_by_uuid(db, data["uuid"])
            if not alarm_group_object:
                # 如果不存在， 则异常返回
                logger.error(f"update alarm group failed, uuid:{data['uuid']} not exist")
                return False

            # 预先保存好之前的数据，方便后续同步失败时，回滚数据库中的数据
            old_alarm_group_info = PromAlarmGroup.get_object_info_by_uuid(db, data["uuid"])

            # 更新数据库
            result = self.update_alarm_group_to_database(db, data)
            if not result:
                logger.error(f"update alarm group to database failed")
                return False

            # 推送到prometheus rule
            result = self.prom_alarm_set_handler.alarm_set_sync_prometheus_rule(db, old_alarm_group_info["alarm_set_uuid"])
            if not result:
                # 推送失败，还原数据
                old_alarm_group_info.pop("alarm_rules")
                old_alarm_group_info.pop("prom_alarm_set")
                self.update_alarm_group_to_database(db, old_alarm_group_info)

                logger.error(f"update_alarm_group: update prometheus rule failed")
                return False
        except Exception as e:
            message = f"update alarm group error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)
        return True



    def update_alarm_group_to_database(self, db: Session, data: dict):
        """
        修改告警规则组信息
        """
        try:
            alarm_group_object = PromAlarmGroup.get_object_by_uuid(db, data["uuid"])
            if not alarm_group_object:
                # 如果不存在， 则异常返回
                logger.error(f"update alarm group failed, uuid:{data['uuid']} not exist")
                return False

            # 更新数据库告警规则组
            result = PromAlarmGroup.update(db, data)
            if not result:
                logger.error(f"update alarm group to database failed")
                return False
        except Exception as e:
            logger.exception(f"update alarm group error => {e}")
            return False

        return True


    def delete_alarm_group(self, db: Session, data: dict):
        """
        满足api调用时，实时更新到prometheus
        """
        try:
            alarm_group_object = PromAlarmGroup.get_object_by_uuid(db, data["uuid"])
            if not alarm_group_object:
                # 如果不存在， 则异常返回
                logger.error(f"delete alarm group failed, uuid:{data['uuid']} not exist")
                return False

            # 预先保存好之前的数据，方便后续同步失败时，回滚数据库中的数据
            old_alarm_group_info = PromAlarmGroup.get_object_info_by_uuid(db, data["uuid"])

            # 更新数据库
            result = self.delete_alarm_group_to_database(db, data)
            if not result:
                logger.error(f"delete alarm group to database failed")
                return False

            # 推送到prometheus rule
            result = self.prom_alarm_set_handler.alarm_set_sync_prometheus_rule(db, old_alarm_group_info["alarm_set_uuid"])
            if not result:
                # 推送失败，还原数据
                old_alarm_group_info.pop("alarm_rules")
                old_alarm_group_info.pop("prom_alarm_set")
                self.add_alarm_group_to_database(db, old_alarm_group_info)

                logger.error(f"delete_alarm_group: update prometheus rule failed")
                return False

        except Exception as e:
            message = f"delete alarm group error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)

        return True


    def delete_alarm_group_to_database(self, db: Session, data: dict):
        """
        删除告警规则组信息
        """
        try:
            # 检查告警规则组是否存在
            alarm_group_object = PromAlarmGroup.get_object_by_uuid(db, data['uuid'])
            if not alarm_group_object:
                logger.error(f"delete alarm group failed, uuid:{data['uuid']} not exist")
                return False

            # 告警规则组内的告警规则是否清空
            alarm_group_info = PromAlarmGroup.get_object_info_by_uuid(db, data['uuid'])
            if len(alarm_group_info["alarm_rules"]) != 0:
                logger.error(f"delete alarm group failed, alarm_rules is not empty")
                return False

            # 删除数据库中的告警组
            PromAlarmGroup.delete_object_by_uuid(db, data['uuid'])
        except Exception as e:
            logger.exception(f"delete alarm group error => {e}")
            return False

        return True


    
    def check_alarm_group(self, db: Session, data: dict):
        # 检查告警规则集是否存在
        alarm_group_object = PromAlarmGroup.get_object_by_name(db, data['name'])
        if not alarm_group_object:
            # 不存在，则增加
            result = self.add_alarm_group_to_database(db, data)
            if not result:
                logger.error(f"check alarm set failed")
                return False

        # 返回告警规则集的信息
        alarm_set_info = PromAlarmSet.get_object_info_by_name(db, data['name'])
        return alarm_set_info



